<?php
class Pageley_ContentManager_Command_ValidateDelete extends Pageley_Controller_Command_TransactionalRead {

    private $ids;
    private $typeName;

    public function setIds($ids) {
        $this->ids = $ids;
    }

    public function setTypeName($typeName) {
        $this->typeName = $typeName;
    }

    protected function executeInternal() {
        $unitOfWork = $this->getUnitOfWork();
        $factory = Pageley_Config::getInstance();
        $type = $factory->valueOf("type." . $this->typeName);
        $siteConfiguration = $factory->valueOf("cm.site");
        $entities = new Pageley_Util_ArrayMap();
        $references = new Pageley_Util_ArrayMap();
        if($this->ids !== null) {
            foreach($this->ids as $id) {
                $entity = $unitOfWork->find($type, $id);
                if($entity === null) {
                    throw new Pageley_Controller_Exception("No entity of type '" . $this->typeName . "' with ID '" . $this->id . "' found.");
                }
                $entities->add($entity);
            }
            $allTypes = $siteConfiguration->getTypes();
            foreach($allTypes as $t) {
                foreach($t->getAttributes() as $name => $attribute) {
                    if($attribute->isReference() && $attribute->getType() == $type) {
                        $refs = $this->findReferences($entities, $t, $name, $unitOfWork);
                        foreach($refs as $reference) {
                            if(!$references->containsValue($reference)) {
                                $references->add($reference);
                            }
                        }
                    }
                }
            }
        }
        $model = new Pageley_Util_ArrayMap();
        $model->put("entities", $entities);
        if(!$references->isEmpty()) {
            $model->put("references", $references);
            throw new Pageley_Controller_Exception("There are still entities referencing the entities of type '" . $this->typeName . "' with ID's " . $this->ids . ": " . $references, 0, null, $this->getFailureAction(), $model);
        }
        return new Pageley_Controller_ModelAndView($model);
    }
    
    private function findReferences($entitiesTo, $typeFrom, $propertyName, $unitOfWork) {
        $query = new Pageley_Query_Basic($typeFrom, new Pageley_Query_Condition_In($propertyName, $entitiesTo));
        return $unitOfWork->query($query);
    }
}